package com.ruoyi.scan.api;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.WxUser;
import com.ruoyi.core.constant.Url;
import com.ruoyi.scan.domain.bo.ApplyBo;
import com.ruoyi.scan.domain.vo.ApplyVo;
import com.ruoyi.scan.service.IApplyService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 入驻申请
 */
@RestController
@RequestMapping(Url.check)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ToApplyController extends BaseController {
    private final IApplyService iApplyService;
    /**
     * 申请入驻接口
     */
    @PostMapping("apply")
    public R<Void> apply(@RequestBody ApplyBo bo){
        Long id = bo.getId();
        WxUser wxUser = getWxUser();

        if(ObjectUtil.isNull(id)){
            //判断用户是否已经申请过了
            Boolean hasRecord = iApplyService.hasRecord(wxUser.getUserId());
            //已经申请过，返回错误，应为修改需要提交id
            if(hasRecord){
                //证明已经提交过
                return fail("您已提交过申请");
            }
            //没有申请过，插入数据
            bo.setUid(wxUser.getUserId());
            bo.setIsCheck("0");
            iApplyService.insertByBo(bo);

            //通知管理员，有人提交了信息。使用redis订阅消息实现
            //TODO
            return ok("提交成功，请等待开发者与您联系或联系开发者。");
        }
        ApplyVo applyVo = iApplyService.queryById(id);
        if(ObjectUtil.isNull(applyVo)){
            return fail("该申请不存在");
        }
        if(!wxUser.getUserId().equals(applyVo.getUid())){
            return fail("权限不足，只能修改自己提交的申请");
        }
        if(!"2".equals(applyVo.getIsCheck())){
            return fail("驳回状态才可以修改");
        }
        bo.setIsCheck("0");
        iApplyService.updateByBo(bo);
        return ok("修改成功");
    }

    @GetMapping("myApply")
    public R<ApplyVo> myApply(){
        WxUser wxUser = getWxUser();
        return ok("查询成功",iApplyService.getApplyByUid(wxUser.getUserId()));

    }
}
